package cn.itcast.jd.task;

import cn.itcast.jd.pojo.Item;
import cn.itcast.jd.service.ItemService;
import cn.itcast.jd.util.HttpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class ItemTask {

    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private ItemService itemService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    //当下载任务完成后，间隔多长时间进行下一次任务
    @Scheduled(fixedDelay = 100 * 1000)
    public void ItemTask() throws Exception{
        //声明需要解析的初始地址
        String url = "https://list.jd.com/list.html?cat=9987%2C653%2C655&s=1&click=0&page=";
        //按照页面对手机的搜索结果进行遍历解析
        for (int i = 1; i < 6; i = i+2) {
            String html = httpUtils.doGet(url + i);
            System.out.println(url);
            System.out.println(html);
            //解析页面，获取商品数据并存储
            this.parse(html);
        }
        System.out.println("手机数据抓取完成");
    }

    /**
     * 解析页面
     * @param html
     */
    public void parse(String html) throws IOException {
        //解析html数据，获取document
        Document doc = Jsoup.parse(html);
        //获取spu信息
        Elements spuEles = doc.select("div#J_goodsList > ul > li");

        for (Element spuEle : spuEles) {
            //获取spu
            long spu = Long.parseLong(spuEle.attr("data-spu"));
            //获取sku信息
            Elements skuEles = spuEle.select("li.ps-item");
            for (Element skuEle : skuEles) {
                //获取sku
                long sku = Long.parseLong(skuEle.select("[data-sku]").attr("data-sku"));
                //根据sku查询商品数据
                Item item = new Item();
                item.setSku(sku);
                List<Item> list = itemService.findAll(item);
                //如果商品存在就进行下一个循环，改商品不保存 因为已经存在
                if(list.size() > 1){
                    continue;
                }
                //获取商品的spu
                item.setSpu(spu);
                //获取商品详情的url
                String itemUrl = "https://item.jd.com/" + sku + ".html";
                item.setUrl(itemUrl);
                //获取商品的图片
                String picUrl = skuEle.select("img[data-sku]").first().attr("data-lazy-img");
                picUrl= picUrl.replace("/n9/", "/n1/");
                String picName = this.httpUtils.doGetImage(picUrl);
                item.setPic(picName);
                //获取商品的价格
                String priceJson = this.httpUtils.doGet("https://p.3.cn/prices/mgets?skuIds=J_" + sku);
                double price = MAPPER.readTree(priceJson).get(0).get("p").asDouble();
                item.setPrice(price);
                //获取商品的标题
                String itemInfo = this.httpUtils.doGet(item.getUrl());
                String title = Jsoup.parse(itemInfo).select("div.sku-name").text();
                item.setTitle(title);
                item.setCreated(new Date());
                item.setUpdated(item.getCreated());

                itemService.save(item);

            }

        }
    }

}
